package com.qidian.buy.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.entity.Content;
import com.qidian.buy.cms.mapper.ContentMapper;
import com.qidian.buy.cms.service.IContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.util.Tools;
import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.Date;
import java.util.HashMap;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2023-07-05
 */
@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements IContentService {

    private List<Timer> timers = new ArrayList<>();

    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public BuyResult queryByCatId(int page, int limit, Long catId) {
        // 先查询缓存
        String key = "CONTENT_"+catId;
        String json = null;
        // 这里的limit是100表示就是查询全部，分页查询的每页最大条数是50
        if(limit == 100 && stringRedisTemplate.hasKey(key) && (json = stringRedisTemplate.opsForValue().get(key)) != null){
            // 缓存有数据
            List<Content> contents = Tools.json2list(json, Content.class);
            Map result = new HashMap<>();
            result.put("records",contents);
            return BuyResult.ok(result);
        }
        // 从数据库查询
        IPage<Content> pager = new Page<>();
        pager.setSize(limit);
        pager.setCurrent(page);
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        wrapper.eq(catId!=null,"category_id",catId);
        pager = contentMapper.selectPage(pager,wrapper);
        if(limit == 100) {
            // 给缓存放一份数据
            stringRedisTemplate.opsForValue().set(key, Tools.object2json(pager.getRecords()));
            // 设置时间
            stringRedisTemplate.expire(key, 30 + (new Random().nextInt(30)), TimeUnit.MINUTES);
        }
        return BuyResult.ok(pager);
    }

    @Override
    public BuyResult saveContent(Content content) {
        // 补全数据
        content.setCreated(new Date());
        content.setUpdated(content.getCreated());
        // 清理缓存
        String key = "CONTENT_"+content.getCategoryId();
        stringRedisTemplate.delete(key);
        if(contentMapper.insert(content)==1){
            // 等一会再删除一次
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 再次删除
                    stringRedisTemplate.delete(key);
                    // 删除完成之后，将timer也删除
                    timers.remove(timer);
                }
            },500);
            // 将timer放入集合
            timers.add(timer);
        }
        return BuyResult.ok();
    }
}
